package cn.vawn.base.interceptor;

import cn.vawn.base.consts.Contants;
import cn.vawn.base.entity.AdminUser;
import cn.vawn.base.util.ParamUtil;
import cn.vawn.base.util.PropertyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
	private static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
//		System.out.println("afterCompletion");
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
//		System.out.println("postHandle");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
//		System.out.println("preHandle");
		request.setCharacterEncoding("UTF-8");
		String requestURI = request.getRequestURI();
		String weChatServerIp = PropertyUtil.getString("app.wechat.server.ip");
		logger.info("weChatServerIp : " + weChatServerIp);
		String clientIp = ParamUtil.getClientIp(request);
        // 系统微信端服务ip
        if (weChatServerIp.equals(clientIp)) {
			logger.info("getClientIp() : " + clientIp);
            return true;
        }
		AdminUser user = (AdminUser) request.getSession().getAttribute(Contants.LOGIN_USER_SESSION_KEY);
		if (user == null) {
			String domain = PropertyUtil.getString("pc.server.domain");
			String url = domain + "/login.html";
			logger.info("url=========>" + url);
//			System.out.println("url=========>" + url);
			response.sendRedirect(url);
			return false;
		}
		return true;
	}
}
